package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private IStrategyCommentService strategyCommentService;

    @Reference
    private ITravelStatisRedisService travelStatisRedisService;

    public TravelController() {
    }

    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo, TravelComment comment) {
        model.addAttribute("pageInfo", travelService.query(qo));




        Page page = travelCommentService.query(new TravelCommentQuery());

        model.addAttribute("tcs" ,page.getContent());
        return "travel/list";
    }


    @RequestMapping("/detail")
    public String detail(Model model, Long id) {

        //detail  游记明细对象  关联内容
        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        detail.setTravelContent(content);
        model.addAttribute("detail", detail);

        //toasts
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        //中国  广东
        Destination dest = toasts.remove(toasts.size() - 1);
        //toasts
        model.addAttribute("toasts", toasts);

        //sds  关联某个目的地下攻略 通过攻略明细的目的地id拿到攻略集合,创建方法根据点赞数排序拿前3个攻略共享进作用域
        List<StrategyDetail> sds = strategyDetailService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("sds", sds);


        //ts  关联某个目的地下游记  通过游记明细的目的地id拿到游记集合,创建方法根据点赞数排序拿前3个游记共享进作用域
        List<Travel> ts = travelService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("ts", ts);

        TravelStatisVO vo = travelStatisRedisService.getTravelStatisVO(id);
        model.addAttribute("vo", vo);

        //阅读量 + 1
        travelStatisRedisService.viewNumIncrease(id, 1);

        //评论list
        TravelCommentQuery qo = new TravelCommentQuery();

        qo.setTravelId(id);  //游记id
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        model.addAttribute("list", page.getContent());

        return "travel/detail";
    }


    @RequestMapping("/input")
    public String input(Model model, Long id) {

        //当前页面传过来的id不为空时,获取游记对象共享给前端
        if (id != null) {
            Travel travel = travelService.get(id);
            //设置游记内容
            travel.setTravelContent(travelService.getContent(id));

            model.addAttribute("tv", travel);
        }

        //共享当前游记的目的地所在层次的所有城市
        model.addAttribute("dests", destinationService.getDestsByDeep(3));


        return "travel/input";
    }


    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }


    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {

        //作者

       /* if (travel.getAuthor().getId() == null) {
            throw new LogicException("请先登录后再操作!");
        } else {*/
        travel.setAuthor(userInfo);

        Long id = travelService.saveOrUpdate(travel);

        return AjaxResult.success().addData(id);
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment, @UserParam UserInfo userInfo) {

        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());

        TravelComment c = travelCommentService.saveOrUpdate(comment);
        model.addAttribute("c", c);
        model.addAttribute("floor",travelCommentService.getCount(comment.getTravelId()));
        //热门排行分数 + 1  : 浏览数+评论数
        travelStatisRedisService.addHotScores(comment.getTravelId(), 1);
        return "/travel/commentTpl";
    }


    //评论收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid, @UserParam UserInfo userInfo){

        if(userInfo == null){  //登录处理
            AjaxResult result  = new AjaxResult(false, "请先登录");
            result.setCode(RedisKeys.CODE.getTime().intValue());  //102 事先约定好未登录状态码
            return result;
        }
        //收藏与取消收藏, 根据返回true/false决定
        boolean ret = travelStatisRedisService.favor(tid, userInfo.getId());
        travelStatisRedisService.addCommendScores(tid, ret?1:-1);
        return new AjaxResult(ret, "").addData(travelStatisRedisService.getTravelStatisVO(tid));
    }

    //评论顶
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object strategyThumbup(Long tid, @UserParam UserInfo userInfo){

        if(userInfo == null){  //登录处理
            AjaxResult result  = new AjaxResult(false, "请先登录");
            result.setCode(RedisKeys.CODE.getTime().intValue());  //102 事先约定好未登录状态码
            return result;
        }
        //点赞
        boolean ret = travelStatisRedisService.thumbup(tid, userInfo.getId());
        //点赞加分
        if(ret){
            travelStatisRedisService.addCommendScores(tid, 1);
        }


        return new AjaxResult(ret, "").addData(travelStatisRedisService.getTravelStatisVO(tid));
    }

}
